# -*- coding: UTF-8 -*-

# Copyright (C) 2009 Daniele Favara.
# Written by Daniele Favara <daniele@zeroisp.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


from restclient.restful_lib import Connection
import urllib
import urllib2
from elementtree.ElementTree import ElementTree, fromstring
import os
import sys
import time
from maps_google_com import MapsGoogleCom
from cStringIO import StringIO

base_url="http://nyc.xml.partners.agoda.com/API/"
et= ElementTree()
TAGLISTS=['roomamenities', 'hotelamenities']

class Agoda():
    def __init__(self, username, password, map_key):
        self.conn = Connection(base_url)
        self.m = MapsGoogleCom(map_key)
        self.username=username
        self.password=password
        self.secure_conn = None

    def get_tree(self, uri, **kw):
        status = ''
        while not status == '200':
            data = urllib.urlencode(kw)
            try:
                ret = self.conn.request_post(uri,args=kw)
                status = ret['headers']['status']
                if status == '200':
                    return fromstring(ret['body'].encode('utf-8'))
            except:
                pass
            #req = urllib2.Request(base_url+uri, data)
            #response = urllib2.urlopen(req)
            #return fromstring(response.readline().encode('utf-8'))



    def _get_child(self, parent):
        ret ={}
        for child in parent.getchildren():
            if not child.getchildren():
                if child.text:
                    ret[child.tag] = child.text
            else:
                if not ret.has_key(child.tag):
                    ret[child.tag] = {}
                if not child.tag in TAGLISTS:
                    ret[child.tag] = self._get_child(child)
                else:
                    ret[child.tag] = []
                    for l in child.getchildren():
                        ret[child.tag].append(l.text)
        return ret
    def _get(self, uri, **kw):
        ret = []
        args = dict(username=self.username,
                    password=self.password)
        for k,v in kw.iteritems():
            args[k]=v
        tree = self.get_tree(uri, **args)
        if tree.tag in ['hotels', 'continents', 'countries', 'cities']:
            for child in tree.getchildren():
                if  child.getchildren():
                    h = self._get_child(child)
                ret.append(h)
        return ret

    def get_geocontinent(self):
        """
        1 Africa
        2 Asia
        3 Central America and Caribbean
        4 Europe
        5 Middle East
        6 North America
        7 Pacific Ocean and Australia
        8 South America
        """
        uri = 'GeoContinent.asmx/Get_geo_continent'
        return self._get(uri)

    def get_geocountry(self, continent_id):
        uri = 'GeoCountry.asmx/Get_geo_country'
        return self._get(uri, continent_id=continent_id)

    def get_geocity(self, country_id):
        uri = 'GeoCity.asmx/Get_geo_city '
        return self._get(uri, country_id=country_id)

    def get_hotel_city(self, city_id):
        uri = 'GetHotelCity.asmx/Get_hotel_city '
        return self._get(uri, city_id=city_id)

    def get_hotel_area(self, area_id):
        uri = 'GetHotelArea.asmx/Get_hotel_area'
        return self._get(uri, area_id=area_id)

    def get_hotel_info(self, hotel_id):
        uri = 'GetHotelInfo.asmx/Get_hotel_info'
        return self._get(uri, list=['hotelamenities','roomamenities'], hotel_id=hotel_id)




def get_hotel_area():
    while status != '200':
        for num in range(1000):
            pass

def get_hotel_info(hote_id):
    while status != '200':
        for num in range(1000):
            ret = conn.request_post("GetHotelInfo.asmx//Get_hotel_info",
                                args=dict(username=username,
                                password=passowrd,hotel_id=num)
                               )
            status = ret['headers']['status']
            if status == '200':
                f = open('tmp.xml', 'w')
                print>> f, ret['body'].encode('utf-8')
                f.close()
                tree = et.parse('tmp.xml')
                """
                  ['append', 'attrib', 'clear', 'find',
                  'findall', 'findtext', 'get', 'getchildren',
                  'getiterator', 'insert', 'items', 'keys',
                  'makeelement', 'remove', 'set', 'tag', 'tail', 'text']
                    hotel_id
                    hotel_name
                    foreign_hotel_name
                    city_id
                    area_id
                    hotel_address_i
                    hotel_room_number
                    hotel_description
                    foreign_hotel_description
                    star_rating
                    hotel_public_notes
                    price_from
                    available
                    hotel_url
                    georeference
                    hotelamenities
                    roomamenities
                """
                if tree.tag == 'hotels':
                    lng = None
                    lat = None
                    country_name_code = None
                    administrative_area_name = None
                    hotel_id = None
                    for hotel in tree.getchildren():
                        for child in hotel.getchildren():
                            if child.text:
                                if child.tag == 'georeference':
                                    for geo in child.getchildren():
                                        if geo.tag == 'Longitude':
                                            lng =  geo.text
                                        elif geo.tag == 'Latitude':
                                            lat = geo.text
                                if child.tag == 'hotel_id':
                                    hotel_id = child.text
                                else:
                                    pass #print child.tag.encode('utf-8'), child.text.encode('utf-8')
                    print lat, lng
                    if lat != None and lng != None:
                        one, two = m.reverse_search(lat,lng)
                        if not os.path.exists('output'):
                            os.makedirs('output')
                        if len(two) > 0:
                            print two[0]
                            country_name_code = two[0].get('country_name_code', 'None')
                            path1 = os.path.join('output', country_name_code)
                            administrative_area_name = two[0].get('administrative_area_name', 'None')
                            path2 = os.path.join(path1, administrative_area_name)
                            sub_administrative_area_name = two[0].get('sub_administrative_area_name', 'None')
                            path3 = os.path.join(path2, sub_administrative_area_name)
                            locality_name = two[0].get('locality_name', 'None')
                            path3 = os.path.join(path3, locality_name)
                            if not os.path.exists(path3):
                                os.makedirs(path3)
                        output = os.path.join(path3, hotel_id + '.xml')
                        f = open(output, 'w')
                        print>> f, ret['body'].encode('utf-8')
                        f.close()

                                    #print '='*5, child.tag


                else:
                    print ret['headers']


